<script type="text/javascript">
function initializeParamFields(paramBlocks)
{
	paramBlocks.each(function (){

		var activeBlock = $(this);
		
		activeBlock.find('.addfbutton').click(
			function (event){
				event.preventDefault();
	
				newfieldname = activeBlock.find('select[name=fieldlist]').val();
	            if (activeBlock.find(".addfields .field_block_"+newfieldname).length) return;
				
	            $.getJSON(
					activeBlock.find(':input[name=new_field_link]').val(),
					{
						'fieldname': newfieldname,
						'fieldarrname': activeBlock.find(':input[name=field_arr_name]').val(),
						'fieldparamspath': activeBlock.find(':input[name=field_params_path]').val(),
						'fieldtemplate': activeBlock.find(':input[name=field_template]').val()
					},
					function(data){
						insertNewField(activeBlock, data);
					}
				);
			}
		);
		
		//---------------------
		activeBlock.find('a.delfieldbtn').click(
			function (event){ delFieldEvent(activeBlock, event, this) }
		);
		//---------------------
	
		if (activeBlock.find("select[name=fieldlist] option").length == 0) activeBlock.find('.fieldlist_block').hide();

	});	
}

function insertNewField(activeBlock, data)
{
	if (0 != data.status)
	{
		alert(data.message);
		return false;
	}

	if (activeBlock.find(".addfields .field_block_"+data.data.field).length) return;

	new_elem = $(data.data.value);
	new_elem.appendTo(activeBlock.find('.addfields'));
	formHighLight(new_elem);

	fieldlist = activeBlock.find('select[name=fieldlist]');

	activeBlock.find('a.delfieldbtn_'+data.data.field).click(
		function (event){ delFieldEvent(activeBlock, event, this) }
	);

	fieldlist.find("option[value='"+data.data.field+"']").remove();
	if (fieldlist.find("option").length == 0) activeBlock.find('.fieldlist_block').hide();
}

function delFieldEvent(activeBlock, event, obj)
{
	event.preventDefault();
	if (confirm('Удалить поле?'))
	{
		var singleFieldBlock = $(obj).closest('.single_field_block');		
		var fieldName = singleFieldBlock.find(':input[name=single_field_name]').val();
		var fieldTitle = singleFieldBlock.find('.field_title').text();

		fieldlist = activeBlock.find('select[name=fieldlist]');
		if (fieldlist.find("option[value='"+fieldName+"']").length == 0)
		{
			$('<option value="'+fieldName+'">'+fieldTitle+'</option>').appendTo(fieldlist);
		}
		
		activeBlock.find('.fieldlist_block').show();

		activeBlock.find(".addfields .field_block_"+fieldName).remove();
	}
}
</script>